package com.cakeshop.dao.impl;

import com.cakeshop.dao.CommentDao;
import com.cakeshop.model.Comment;
import com.cakeshop.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * TODO
 *
 * @author nineice
 * @date 2021/8/24 8:45
 */
public class CommentDaoImpl implements CommentDao {
    @Override
    public void insertComment(Comment comment) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "insert into `comment`(username, commentDate, commentContent, likeNum, noLikeNum, reply) values(?,?,?,0,0,null)";
        r.update(sql, comment.getUsername(), comment.getCommentDate(), comment.getCommentContent());
    }

    @Override
    public void updateById(Comment comment) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "update `comment` set likeNum = ?, noLikeNum = ?, reply = ? where id = ?";
        r.update(sql, comment.getLikeNum(), comment.getNoLikeNum(), comment.getReply(), comment.getId());
    }

    @Override
    public void deleteById(int id) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "delete from `comment` where id = ?";
        r.update(sql, id);
    }

    @Override
    public List<Comment> findAll() throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "select * from `comment`";
        return r.query(sql, new BeanListHandler<Comment>(Comment.class));
    }

    @Override
    public Comment findById(int id) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "select * from `comment` where id = ?";
        return r.query(sql, new BeanHandler<>(Comment.class), id);
    }
}
